
//
//  TZHttpTool.m
//
//  Created by tanzhen on 15-8-25.
//  Copyright (c) 2015年 ttouch. All rights reserved.
//

#import "TZHttpTool.h"

@implementation TZHttpTool

+ (void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *error))failure {
    // 1.创建请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/vnd.geo+json", @"text/json", @"text/javascript",@"text/html", nil];
    // 2.发送请求
    [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (failure) {
            failure(error.localizedDescription);
        }
    }];
}

+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *msg))failure {
    // 1.创建请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    // 2.发送请求
    [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSNumber *number = responseObject[@"error"];
        if (number.integerValue == 1 || number.integerValue == 200) {
            if (success) {
                success(responseObject);
            }
        } else if (number.integerValue == 0) {
            if (failure) {
                failure(responseObject[@"msg"]);
            }
        }  else if (number.integerValue == 101)  {
            if (success) {
                success(responseObject);
            }
        }else {
            if (failure) {
                failure(responseObject[@"msg"]);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (failure) {
            failure(error.localizedDescription);
        }
    }];
}

/// 上传多张图片

+ (void)uploadOperationToUrl:(NSString *)url
                      params:(NSDictionary *)params
                       files:(NSArray *)files
                     process:(void (^)(NSInteger writedBytes, NSInteger totalBytes))process
                 completeOne:(void (^)(BOOL successed, NSDictionary *result))completeOne
                    complete:(void (^)())complete {
    NSMutableArray *mutableOperations = [NSMutableArray array];
    
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    for (NSInteger i = 0; i < files.count; i++) {
        id fileItem = files[i];
        id value = fileItem;
        NSString *fileName = [NSString stringWithFormat:@"image%zd.png",i];
        NSString *key = @"img";
        NSString *mimeType = @"image/jpeg";
        if ([fileItem isKindOfClass:[NSDictionary class]]) {
            value = [fileItem objectForKey:@"file"];     // 支持四种数据类型：NSData、UIImage、NSURL、NSString
            key = [fileItem objectForKey:@"key"];        // 文件字段的key
            fileName = [fileItem objectForKey:@"name"];  // 文件名称
            mimeType = [fileItem objectForKey:@"type"];  // 文件类型
            mimeType = mimeType ? mimeType : @"image/jpeg";
        }
        NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if ([value isKindOfClass:[NSData class]]) {
                [formData appendPartWithFileData:value name:key fileName:fileName mimeType:mimeType];
            } else if ([value isKindOfClass:[UIImage class]]) {
                [formData appendPartWithFileData:UIImageJPEGRepresentation(value, 0.5) name:key fileName:fileName mimeType:mimeType];
            } else if ([value isKindOfClass:[NSURL class]]) {
                [formData appendPartWithFileURL:value name:key fileName:fileName mimeType:mimeType error:nil];
            } else if ([value isKindOfClass:[NSString class]]) {
                [formData appendPartWithFileURL:[NSURL URLWithString:value] name:key fileName:fileName mimeType:mimeType error:nil];
            }
        } error:nil];
        
        AFHTTPRequestOperation *operation = nil;
        AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
        operationManager.responseSerializer.acceptableContentTypes = nil;
        operation = [operationManager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (completeOne) { completeOne(true, responseObject); }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (completeOne) { completeOne(false, nil); }
        }];
        [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
            NSLog(@"文件上传进度: %.0f%% (%lld/%lld)",100*progress,totalBytesWritten,totalBytesExpectedToWrite);
            if (process) {
                process((NSUInteger)totalBytesWritten,(NSUInteger)totalBytesExpectedToWrite);
            }
        }];
        [mutableOperations addObject:operation];
    }
    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
        NSLog(@"已上传%zd个文件，共%zd个文件", numberOfFinishedOperations, totalNumberOfOperations);
    } completionBlock:^(NSArray *operations) {
        NSLog(@"所有文件上传完成");
        if (complete) {  complete(); }
    }];
    [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
}

/// 上传单张图片
+ (void)uploadImageWithUrl:(NSString *)url params:(NSDictionary *)params image:(UIImage *)image completion:(void (^)(NSDictionary *result, NSError *error))completion {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"imageName.png" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (completion) {
            id res = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            completion(res[@"data"], nil);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        if (completion) {
            completion(nil, error);
        }
    }];
}

#pragma mark - 私有方法


//json字符串转日历
+(NSString *)getNewDate:(NSString *)dateStr{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateStr integerValue]];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [df stringFromDate:date];
    
    return timeStr;
}

@end
